<?php
namespace wechat;

use EasyWeChat\Factory;
use think\Exception;

class MediaCheckAsync{
    /**
     * 微信音视频内容安全识别
     * @author lichunguang
     * @since 2024/5/18 13:17
     * @param $appId
     * @param $appSecret
     * @param $uid
     * @param $openid
     * @param $content
     * @return true
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function checkMedia($appId, $appSecret, $uid, $openid, $media_type, $media_url){
        //以下微信文本校验
        $config = [
            'app_id' => $appId,
            'secret' => $appSecret,
        ];
        $app          = Factory::miniProgram($config);
        $token        = $app->access_token->getToken();
        $access_token = $token['access_token'];
        $phoneDataRes = $app->access_token->request('https://api.weixin.qq.com/wxa/media_check_async?access_token=' . $access_token, 'POST', [
            'json' => [
                "openid" => $openid,
                "scene" => 1,
                "version" => 2,
                'media_type' => $media_type,
                'media_url' => $media_url
            ]
        ]);
        $checkResult    = json_decode($phoneDataRes->getBody()->getContents(), true);
        if ($checkResult['errcode'] != 0) {
            throw new \Exception($checkResult["errmsg"]);
        }
        //保存音视频审核记录
        $traceId = $checkResult['trace_id'] ?? '';
        $data = [
            'u_id' => $uid,
            'openid' => $openid,
            'media_url' => $media_url,
            'media_type' => $media_type,
            'trace_id' => $traceId,
            'createtime' => time()
        ];
        db('zh_wechat_media_log')->insertGetId($data);
        return $traceId;
    }
}